<template>
  <a-card>
    <!-- 表格区域 -->
    <div>
      <div class="operator">
        <a-button
          v-permission="`inspection:branch:add`"
          class="mr-8"
          type="primary"
          @click="handleAddBranch"
          >新增</a-button
        >
        <a-button
          v-permission="`inspection:branch:batchDel`"
          type="danger"
          :class="{ 'btn-disabled': !rowSelection.selectedRowKeys.length }"
          @click="handleDelAll"
          >批量删除</a-button
        >
      </div>
    </div>
    <a-table
      :columns="columns"
      :row-key="item => item.id"
      :pagination="pagination"
      :data-source="dataSource"
      :loading="loading"
      @change="handleTableChange"
      :row-selection="rowSelection"
      bordered
    >
      <span slot="tags" slot-scope="departments">
        <a-tag v-for="item in departments" :key="item.id" color="green">{{ item.deptName }}</a-tag>
      </span>
      <span slot="action" slot-scope="item">
        <a v-permission="`inspection:branch:update`" @click="handleEditBranch(item)">修改</a>
        <a-divider type="vertical" />
        <a v-permission="`inspection:branch:del`" class="text-danger" @click="handleDelBranch(item)"
          >删除</a
        >
      </span>
    </a-table>

    <!-- 新增/修改弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="支部名称"
        >
          <a-input
            v-decorator="['branchName', { rules: [{ required: true, message: '请输入名称' }] }]"
            placeholder="请输入名称"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="支部说明"
        >
          <a-textarea
            v-decorator="['branchDesc', { rules: [] }]"
            placeholder="支部说明"
            :rows="4"
          />
        </a-form-item>
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="关联部门"
        >
          <a-select
            mode="multiple"
            v-decorator="['branchDept', { rules: [{ required: true, message: '请关联部门' }] }]"
            placeholder="关联部门，部门可多选"
          >
            <a-select-option :value="item.id" v-for="item in deptList" :key="item.id">{{
              item.deptName
            }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { basicService, inspectionService } from '@/services';

const columns = [
  {
    title: '支部ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
    width: 150,
  },
  {
    title: '名称',
    dataIndex: 'branchName',
    key: 'branchName',
    align: 'center',
    width: 200,
  },
  {
    title: '说明',
    dataIndex: 'branchDesc',
    key: 'branchDesc',
    align: 'center',
  },
  {
    title: '关联部门',
    key: 'departments',
    dataIndex: 'departments',
    scopedSlots: { customRender: 'tags' },
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 200,
  },
];

const formItemLayout = {
  labelCol: { span: 4, offset: 2 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'inspectionBranch',

  data() {
    return {
      columns: columns,
      dataSource: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      loading: false,
      visible: false,
      type: 1, // 1-新增 2-修改
      formItemLayout,
      form: this.$form.createForm(this, { name: 'add_branch' }),
      confirmLoading: false,
      deptList: [],
      selectedItem: null, // 修改时的选中项
      rowSelection: {
        selectedRowKeys: [],
        onChange: selectedRowKeys => (this.rowSelection.selectedRowKeys = selectedRowKeys),
      },
    };
  },

  computed: {
    modalTitle() {
      return this.type === 1 ? '新增' : '修改';
    },
  },

  created() {
    this.getDataSource(this.pagination);
  },

  methods: {
    // 获取数据
    getDataSource({ current, pageSize }) {
      console.log({ current, pageSize });
      this.loading = true;
      inspectionService.getBranchList({ pageNo: current, pageSize, needDetail: true }).then(res => {
        console.log(res);
        this.dataSource = res.data.content;
        this.dataSource.forEach(item => {
          item.relatedDepartments = item.relatedDepartments
            ? item.relatedDepartments.split(',')
            : [];
        });
        this.pagination.total = res.data.totalElements;
        this.pagination.current = current;
        this.pagination.pageSize = pageSize;
        this.loading = false;
      });
    },

    // 获取部门数据
    getDeptList() {
      basicService.getDeptList({ needDetail: true, canChoose: true }).then(res => {
        if (res.code === '200') {
          if (this.type === 1) {
            this.deptList = res.data.items;
          } else {
            this.deptList = res.data.items.concat(this.selectedItem.departments);
          }
        }
      });
    },

    // 分页切换
    handleTableChange(pagination) {
      console.log(pagination);
      this.getDataSource(pagination);
    },

    // 新增支部
    handleAddBranch() {
      this.type = 1;
      this.visible = true;
      this.getDeptList();
    },

    // 修改支部
    handleEditBranch(item) {
      console.log(item);
      this.type = 2;
      this.visible = true;
      this.getDeptList();
      this.selectedItem = item;
      this.$nextTick(() => {
        this.form.setFieldsValue({
          branchName: item.branchName,
          branchDesc: item.branchDesc,
          branchDept: item.departments.map(item => item.id),
        });
      });
    },

    // 删除支部
    handleDelBranch(item) {
      console.log(item);
      const that = this;
      this.$confirm({
        title: '确认删除该支部吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const { id } = item;
          console.log(id);
          return new Promise(resolve => {
            inspectionService
              .delBranch({ id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('删除成功');
                  that.getDataSource(that.pagination);
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 新建/修改支部确认
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log('Received values of form: ', values);
          if (this.type === 1) {
            inspectionService
              .addBranch(values)
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('新增成功');
                  this.visible = false;
                  this.form.resetFields();
                  this.getDataSource(this.pagination);
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else {
            inspectionService
              .updateBranch({ ...values, id: this.selectedItem.id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('修改成功');
                  this.visible = false;
                  this.selectedItem = null;
                  this.form.resetFields();
                  this.getDataSource(this.pagination);
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    // 取消新建支部
    handleCancel() {
      this.visible = false;
      this.selectedItem = null;
      this.form.resetFields();
    },
    // 批量删除
    handleDelAll() {
      console.log('批量删除', this.rowSelection.selectedRowKeys);
      const that = this;
      this.$confirm({
        title: '确认批量删除该些支部吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const idList = that.rowSelection.selectedRowKeys;
          return new Promise(resolve => {
            inspectionService
              .delBranchList({ idList })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('删除成功');
                  that.getDataSource(that.pagination);
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import './index.less';
</style>
